using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

namespace LS.Editor
{
    public static class LSPathEditor
    {
        public static readonly string LSFrameworkRootName = "ls-framework";
        public static readonly string LSFrameworkEditorRootPath = $"{LSFrameworkRootName}/Editor";
        public static readonly string LSFrameworkRuntimeRootPath = $"{LSFrameworkRootName}/Runtime";

        public static readonly string LSFrameworkEditorAssetsPath = $"{LSFrameworkEditorRootPath}/Assets";
        public static readonly string LSFrameworkEditorScriptsPath = $"{LSFrameworkEditorRootPath}/Scripts";
        public static readonly string LSFrameworkRuntimeScriptsPath = $"{LSFrameworkRuntimeRootPath}/Scripts";
        public static readonly string LSFrameworkRuntimeAssetsPath = $"{LSFrameworkRuntimeRootPath}/Assets";

        internal static readonly string LSPluginsEditorAssetRootPath = "Packages/com.lancerstudio.lsframework/Editor/Assets";

        public static void CreateDirectoryWithoutExisted(string namePath)
        {
            if (!Directory.Exists(namePath))
            {
                Directory.CreateDirectory(namePath);
            }
        }

        public static void DeleteFileWhenExisted(string namePath)
        {
            if (File.Exists(namePath))
            {
                File.Delete(namePath);
            }
        }

        public static void DeleteDirectoryWhenExisted(string namePath)
        {
            if (Directory.Exists(namePath))
            {
                Directory.Delete(namePath, true);
            }
        }

        public static void WriteAllText(string namePath,string text)
        {
            string directory = Path.GetDirectoryName(namePath);
            string filePath = namePath;
            CreateDirectoryWithoutExisted(directory);
            File.WriteAllText(filePath, text);
        }
        
        public static T[] FindAssetsFromProject<T>(string fileName = null, string[] searchPath = null) where T : Object
        {
            string filter = $"{typeof(T).FullName}";

            if (!string.IsNullOrEmpty(fileName))
            {
                filter += $"l:{Path.GetFileNameWithoutExtension(fileName)}";
            }
            if (searchPath == null)
            {
                searchPath = new string[] { "Assets" };
            }

            string[] ids = AssetDatabase.FindAssets($"t:{filter}", searchPath);

            T[] assets = new T[ids.Length];

            if (ids.Length == 0) return assets;

            for (int i = 0; i < ids.Length; i++)
            {
                string path = AssetDatabase.GUIDToAssetPath(ids[i]);
                assets[i] = AssetDatabase.LoadAssetAtPath<T>(path);
            }
            return assets;
        }
    }
}
